from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from .models import QQUser
from django.contrib.auth import login
from .utils import generate_access_token, check_access_token
import json,re
from django_redis import get_redis_connection
from .models import User
from apps.carts.utils import merge_cart_cookie_to_redis

# Create your views here.


class QQFirstView(View):
    """获取QQ扫码登录页面"""

    def get(self,request):

        # 提取 next 参数
        next = request.GET.get('next')

        # 创建初始化对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 获取QQ 扫码登录地址
        qq_login_url = oauth.get_qq_url()

        # 返回响应
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'login_url': qq_login_url})

class QQUserView(View):
    """用户扫码成功后回调处理"""

    def get(self,request):

        # 提取参数
        code = request.GET.get('code')

        # 创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        try:
            # 获取access_token
            access_token = oauth.get_access_token(code)

            # 获取 openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                 'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'})

        # 判断是否绑定了QQ
        try:
            qq_user = QQUser.objects.get(openid=openid)
        except Exception as e:
            # 如果未绑定,将openid 加密为 access_token并返回
            token = generate_access_token(openid)

            return http.JsonResponse({'code':300, 'errmsg': 'ok', 'access_token': token})

        else:
            # 如果已绑定,则状态保持,并返回响应
            login(request,qq_user.user)

            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', qq_user.user.username)

            return response

    def post(self,request):
        """美多商城用户绑定openid"""

        # 接收参数
        data_dict = json.loads(request.body)

        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code = data_dict.get('sms_code')
        access_token = data_dict.get('access_token')

        # 校验参数
        if not all([mobile, password, sms_code, access_token]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 单独校验
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '请输入8-20位的密码'})

        # 短信验证码校验
        redis_conn = get_redis_connection('verify_code')

        try:
            sms_code_server = redis_conn.get('sms_%s' % mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg' : '短信验证码过期'})

        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg' : '短信验证码错误'})

        openid = check_access_token(access_token)

        # 判断是否为已注册用户
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 用户未注册, 创建用户并绑定openid
            try:
                user = User.objects.create_user(username=mobile,
                                                mobile=mobile,
                                                password=password)
            except Exception as e:
                return http.JsonResponse({'code': 400, 'errmsg' : '创建用户失败'})

            try:
                qq_user = QQUser.objects.create(user=user,
                                                openid=openid)
            except Exception as e:
                return http.JsonResponse({'code': 400, 'errmsg' : '绑定QQ失败'})

            # 状态保持
            login(request, user)

            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', user.username, max_age=3600*24*14)

            return response

        else:
            # 如果用户已注册,校验密码,并绑定openid
            if not user.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg' : '用户名或者密码错误'})

            try:
                qq_user = QQUser.objects.create(user=user,
                                                openid=openid)
            except Exception as e:
                return http.JsonResponse({'code': 400, 'errmsg' : '绑定QQ失败'})

            # 状态保持
            login(request, user)

            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

            return merge_cart_cookie_to_redis(request, user, response)




